<?php

//session_start();
/*
 * Authcore
 * 
 * Libreria para realizar la validación de usuarios en el core WEB CODEIGNITER
 * 
 * v 1.0 : Gustavo Delgado
 * 
 * 
 */
class Authcore {

    private $_controller;
    private $_action;
    private $_user_id;
    private $_perfil_id;
    private $_resources;
    public $ci;
    private $_resourceId;

    public function __construct($config = array()) {
        $this->ci = &get_instance();
        $this->ci->load->model('auth_model');
        $this->_controller = $this->ci->router->fetch_class();
        $this->_action = $this->ci->router->fetch_method();
        $this->_preDispatcher();
    }

    private function _isLogged() {
        $return = false;
        if ($this->ci->session->userdata('logged_in')) {
            $this->_user_id = $this->ci->session->userdata('id_usuario');
            $this->_perfil_id = $this->ci->session->userdata('id_perfil');
            $this->_resources = $this->ci->session->userdata('resources');
            $return = true;
        } else {
            $return = false;
        }
        return $return;
    }

    public function getSSUserId() {
        return $this->_user_id;
    }

    public function getSSRolId() {
        return $this->_perfil_id;
    }

    private function _preDispatcher() {
        if (!$this->_isLogged()) {
            if ($this->_controller !== 'auth') {
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
                        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    $data = array(
                        'session' => false,
                        'errors' => array(
                            'Error de Permisos' => 'Expiro el tiempo de connexion.'),
                        'results' => 0,
                        'rows' => array(),
                        'msg' => 'Expiro el tiempo de conexion'
                    );
                    echo json_encode($data);
                    exit;
                } else {
                    redirect('auth/index', 'location');
                }
            } elseif ($this->_controller === 'auth') {
                if ($this->_action === 'login') {
                    $uid = $this->ci->input->post('userid');
                    $pass = $this->ci->input->post('password');
                    $groups_id = $this->ci->input->post('groups_id');

                    $user = $this->ci->auth_model->login($uid, $pass);

                    $groupsConfig = json_decode("[" . $user->groups . "]");
                    
                    //print_r($user);exit;

                    if ($user != null) {
                        $permitedViews = $this->ci->auth_model->getPermitedViews(null, $user->_rols_id);
                        if ($user->status === 'ENABLED') {
                            
                            $uploadFolder = $this->ci->config->item("upload_folder");
                            $server = $this->ci->config->item("base_url") . "upload/";
                            
                            $credentials = array(
                                'groups_id' => $groups_id,
                                'id_usuario' => $user->id,
                                'id_perfil' => $user->_rols_id,
                                'uid' => $user->email,
                                'nombre' => $user->names . ' ' . $user->lastnames,
                                'logged_in' => true,
                                'groups' => $groupsConfig,
                                'uploadfolder'=>$server . "users/" . $user->_rols_id . "/" . $user->email,
                                'resources' => $permitedViews
                            );

                            

                            $userFolderCfg = Array(
                                'name' => $user->email,
                                'url' => $server . "users/" . $user->_rols_id . "/" . $user->email,
                                'directory' => $uploadFolder . "users/" . $user->_rols_id . "/" . $user->email,
                                'maxSize' => "100M",
                                'allowedExtensions' => 'avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,swf,txt,wav,wma,wmv,xls,xlsx,bmp,gif,jpeg,jpg,png,avi,mp3,swf,flv',
                                'deniedExtensions' => 'exe,bin,dll,sh,bat,gz,tar,rar'
                            );

                            //ci session por defecto para app web
                            $this->ci->session->set_userdata($credentials);

//                            //php session necesario para ckfinder
                            $_SESSION['id_usuario'] = $user->id;
                            $_SESSION['ss_user_res'] = $userFolderCfg;
                            
                            redirect('index/index', 'location');
                        } else {
                            log_message("error","usuario no activo");
                            redirect('auth/index', 'location');
                        }
                    } else {
                        redirect('auth/index', 'location');
                    }
                } else if ($this->_action === 'logout') {
                    $this->ci->session->sess_destroy();
                    redirect('auth/index', 'location');
                } else {
                    
                }
            }
        } else {
            $uid = $this->getSSUserId();
            $perfilId = $this->getSSRolId();
            $views = $this->_resources;
            if (!empty($uid) && !empty($perfilId)) {
                if ($this->ci->auth_model->hasPermission($this->_controller, $this->_action, $perfilId)) {
                    log_message('info', 'usuario:' . $uid . ', permitido: ' . $this->_controller . '/' . $this->_action);
                } else {
                    if ($this->_controller === 'index' && $this->_action === 'index') {
                        log_message('info', 'usuario:' . $uid . ', permitido: ' . $this->_controller . '/' . $this->_action);
                    } else {
                        if ($this->_controller === 'auth' && $this->_action === 'logout') {
                            log_message('info', 'usuario:' . $uid . ', cerrando sesion: ');
                        } elseif ($this->_controller === 'auth' && ($this->_action === 'index' || $this->_action === 'login' )) {
                            redirect('index/index', 'location');
                        } else {
                            if ($this->_action !== 'index') {
                                $data = array(
                                    'success' => false,
                                    'errors' => array(
                                        'Error de Permisos' => 'Usted no tiene permisos para ejecutar la operacion solicitada.'),
                                    'results' => 0,
                                    'rows' => array(),
                                    'msg' => 'Sin permisos para ejecutar la opración'
                                );
                                log_message('info', 'usuario:' . $uid . ', sin permisos en ' . $this->_controller . '/' . $this->_action);
                                echo json_encode($data);
                            } else {
                                if (empty($this->_action) && empty($this->_controller)) {
                                    redirect('index/index', 'location');
                                } else {
                                    echo '<h1 style="color:red">Error de acceso, sin permisos necesarios.</h1>';
                                }
                            }
                            exit;
                        }
                    }
                }
            }
        }
    }
}

?>